<template>
  <div class="app-container">
    <!-- 头部操作栏 -->
    <div class="header">
      <div class="action-group">
        <el-button type="primary" @click="handleCreate" :icon="Plus">新增用户</el-button>
        <el-button type="danger" :disabled="selectedIds.length === 0" @click="handleBatchDelete">
          批量删除（{{ selectedIds.length }}）
        </el-button>
      </div>
      <el-input
        v-model="searchKeyword"
        placeholder="搜索用户"
        style="width: 250px; margin-left: 20px"
        clearable
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <!-- 用户表格 -->
    <el-table
      :data="users"
      stripe
      style="width: 100%; margin-top: 20px"
      :header-cell-style="{ background: '#f5f7fa' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" width="60" label="序号" align="center" />

      <el-table-column prop="phone" label="电话号码" width="150" align="center" />
      <el-table-column prop="username" label="用户名" width="120" align="center" />
      <el-table-column prop="identity" label="身份" width="150" align="center" />
      <el-table-column prop="createTime" label="创建时间" width="180" align="center" />

      <el-table-column prop="status" label="状态" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status ? 'success' : 'danger'">
            {{ row.status ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="150" align="center">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)" type="primary" plain
            >编辑</el-button
          >
          <el-button size="small" @click="handleDelete(scope.row.id)" type="danger" plain
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      class="pagination"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[2, 5, 8]"
      :current-page="pageNum"
      :page-size="pageSize"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="formData" :rules="formRules" ref="userForm" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入电话号码" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status">
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>

        <el-form-item label="角色" prop="identity">
          <el-select v-model="formData.identity" placeholder="请选择角色">
            <el-option label="普通用户" value="user" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import { queryByPageService, updateService, addService, batchDeleteService } from '@/api/user'
import _ from 'lodash'

const users = ref([])
const total = ref(0)

const searchKeyword = ref('')
const dialogVisible = ref(false)
const formData = ref({
  id: null,
  username: '',
  phone: '',
  identity: 'user',
  status: '1',
})
const isEditMode = ref(false)
const userForm = ref(null)

// 分页相关
const pageNum = ref(1)
const pageSize = ref(8)
const selectedIds = ref([])

// 统一获取数据方法
const fetchUsers = async () => {
  const params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    keyword: searchKeyword.value,
  }
  const res = await queryByPageService(params)
  users.value = res.data.data.records
  total.value = res.data.data.total
}

// 分页事件处理
const handleSizeChange = async (newSize) => {
  pageSize.value = newSize
  pageNum.value = 1
  await fetchUsers()
}

const handleCurrentChange = async (newPage) => {
  pageNum.value = newPage
  await fetchUsers()
}

// 搜索处理（带防抖）
const handleSearch = _.debounce(() => {
  pageNum.value = 1
  fetchUsers()
}, 500)

// 多选处理
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map((item) => item.id)
}

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在3到20个字符', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
  ],

  identity: [{ required: true, message: '请选择角色', trigger: 'change' }],
}

// 创建用户
const handleCreate = () => {
  isEditMode.value = false
  formData.value = { id: null, username: '', phone: '', identity: 'user', status: '1' }
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  isEditMode.value = true
  formData.value = { ...row, status: row.status.toString() }
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  await userForm.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEditMode.value) {
          await updateService(formData.value)
          ElMessage.success('更新成功')
        } else {
          Object.assign(formData.value, { password: '123456' })
          const res = await addService(formData.value)
          if (res.data.code == 1) ElMessage.success('创建成功')
          else ElMessage.error('该手机号已注册')
        }
        dialogVisible.value = false
        await fetchUsers()
      } catch (error) {
        console.error('操作失败:', error)
      }
    }
  })
}

// 删除用户
const handleDelete = async (id) => {
  console.log(id)
  try {
    await ElMessageBox.confirm('确认删除该用户？', '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
    const res = await batchDeleteService([id])
    console.log(res)
    ElMessage.success('删除成功')
    await fetchUsers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(`确认删除选中的${selectedIds.value.length}个用户？`, '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await batchDeleteService(selectedIds.value)
    ElMessage.success('批量删除成功')
    await fetchUsers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
    }
  }
}

// 对话框标题
const dialogTitle = computed(() => {
  return isEditMode.value ? '编辑用户' : '新增用户'
})

// 初始化加载数据
onMounted(async () => {
  await fetchUsers()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  padding: 15px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.el-table {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding: 15px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-dialog {
  border-radius: 12px;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-select {
  width: 100%;
}

.action-group {
  display: flex;
  gap: 10px;
  align-items: center;
}

.el-button[type='danger'][disabled] {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>
